// 手写一个简单的jquery
const mj = function (selector) {
  return new MyJquery(selector);
};

class MyJquery {
  constructor (selector) {
    this.selector = selector;
    this.context = document;
    this.length = 0;
    const res = this.query();
    if (res) {
      if (Array.isArray(res)) {
        this.length = res.length;
        for (var i = 0; i < res.length; i++) {
          this[i] = res[i];
        }
      } else {
        this.length = 1;
        this[0] = res;
      }
    }
  }

  each (callback) {
    for (var i = 0; i < this.length; i++) {
      callback.call(this, this[i]);
    }
    return this;
  }

  query () {
    let div;
    if (this.selector.startsWith('.')) { // 类
      div = document.getElementsByTagName(this.selector);
    } else if (this.selector.startsWith('#')) { // id
      div = document.getElementById(this.selector.substr(1));
    } else {
      div = document.getElementsByTagName(this.selector);
    }
    return div;
  }

  show (bool) {
    if (this.length) {
      if (bool === undefined || bool) {
        this.each((dom) => {
          dom.style.display = 'block';
        });
      } else {
        this.each((dom) => {
          dom.style.display = 'none';
        });
      }
    }
    return this;
  }

  hide () {
    return this.show(false);
  }
}

var wrapper = mj('#wrapper');
wrapper.show(false);
